#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Build-in / Std

'''
Created on 2016年9月1日

@author: Hawk
'''
import sys
import datetime
import wx
import MDIChildFrameBase
import BaseDialog
from model.Model import *
from action.Action import *
from ControlID import ControlID

class AddProductDialog(BaseDialog.BaseDialog):
    def __init__(self, *args, **kwds):
        BaseDialog.BaseDialog.__init__(
            self, None, -1, u'Add Record',
            style=wx.CAPTION | wx.CLOSE_BOX,
            size=(470, 330))

        self.project_list = Project.select().where(Project.deleted == False)
        self.project_list_title = [pro.name for pro in self.project_list]
        self.label_project = wx.StaticText(self, -1, u"Project", pos=(20, 15))
        self.project_choice = wx.Choice(self, -1, pos=(80, 15), choices=self.project_list_title)
        self.project_choice.Bind(wx.EVT_CHOICE, self.OnProjectChoiceSelect)

        self.label_sku = wx.StaticText(self, -1, u"Sku", pos=(20, 50)) # 200, 15
        self.skulist_listBox = wx.CheckListBox(self, -1, size=(100, 100), pos=(80, 50), style=wx.LB_SINGLE)

        #self.sku_list = Sku.select().where(Sku.deleted == False)
        #self.sku_list_title = [s.name for s in self.sku_list]
        #self.skulist_listBox.Set(self.sku_list_title)

        self.label_release_date = wx.StaticText(self, -1, u"Release Date", pos=(240, 15)) # 20, 85
        self.release_date_ctrl = wx.DatePickerCtrl(self, -1, size=(100, 20), pos=(340, 15), # 80, 85
                                                  style=wx.DP_DROPDOWN)

        self.label_develop_mm = wx.StaticText(self, -1, u"Develop MM", pos=(240, 45))
        self.textctrl_develop_mm = wx.TextCtrl(self, -1, size=(100, 20), pos=(340, 45))

        self.label_maintain_mm = wx.StaticText(self, -1, u"Maintain MM", pos=(240, 75))
        self.textctrl_maintain_mm = wx.TextCtrl(self, -1, size=(100, 20), pos=(340, 75))

        self.label_version = wx.StaticText(self, -1, u"Version", pos=(240, 105))
        self.textctrl_version = wx.TextCtrl(self, -1, size=(100, 20), pos=(340, 105))

        self.label_ww_version = wx.StaticText(self, -1, u"WW Version", pos=(240, 135))
        self.textctrl_ww_version = wx.TextCtrl(self, -1, size=(100, 20), pos=(340, 135))

        self.label_is_sync_ww = wx.StaticText(self, -1, u"Sync WW", pos=(240, 160))
        self.checkbox_is_sync_ww = wx.CheckBox(self, -1, "", size=(100, 20), pos=(340, 160))

        self.label_ww_release_date = wx.StaticText(self, -1, u"WW DRL Date", pos=(240, 185)) # 20, 85
        self.ww_release_date_ctrl = wx.DatePickerCtrl(self, -1, size=(100, 20), pos=(340, 185), # 80, 85
                                                  style=wx.DP_DROPDOWN)

        # Hide before sync ww checked
        self.label_ww_release_date.Show(False)
        self.ww_release_date_ctrl.Show(False)

        self.BinCheckBox(self.checkbox_is_sync_ww, ControlID.CHECKBOX_ID_IS_SYNC_WW, self.OnCheckBoxChanged)

        self.label_comment = wx.StaticText(self, -1, u"Comment", pos=(20, 210))
        self.textctrl_comment = wx.TextCtrl(self, -1, size=(360, 20), pos=(80, 210))

        self.button_save = wx.Button(self, -1, u"Save", pos=(180, 240))
        self.Bind(wx.EVT_BUTTON, self.OnSaveButtonClicked, self.button_save)

    def OnCheckBoxChanged(self, event, id, **kwargs):
        if id == ControlID.CHECKBOX_ID_IS_SYNC_WW:
            cb = event.GetEventObject()
            if cb.GetValue():
                self.label_ww_release_date.Show(True)
                self.ww_release_date_ctrl.Show(True)
            else:
                self.label_ww_release_date.Show(False)
                self.ww_release_date_ctrl.Show(False)

    def OnProjectChoiceSelect(self, event):
        selected_project_name = self.project_choice.GetString(self.project_choice.GetSelection())
        #self.showMessageBox()
        self.UpdateSkuList(selected_project_name)
        pass

    def GetItemByItemAttr(self, data_list, attr_value_list, attr_name):
        return_data_list = []
        for item in data_list:
            if getattr(item, attr_name) in attr_value_list:
                return_data_list.append(item)
        return return_data_list

    def UpdateSkuList(self, selected_project_name):
        selected_project = Project.select().where(Project.name == selected_project_name).get()
        self.sku_list = [item.sku for item in Product.select().where(Product.project == selected_project)]
        self.sku_list_title = [s.name for s in self.sku_list]
        self.skulist_listBox.Set(self.sku_list_title)
        pass

    def OnSaveButtonClicked(self, event):
        project_name = self.project_choice.GetString(self.project_choice.GetSelection())
        selected_project = Project.getOne(Project.name == project_name)
        if selected_project is None:
            self.showMessageBox(u'选择Project')
            return

        checked_strings = self.skulist_listBox.GetCheckedStrings()
        checked_strings_count = len(checked_strings)
        if checked_strings_count <= 0:
            self.showMessageBox(u'需要选择涉及的Sku')
            return

        selected_skus = self.GetItemByItemAttr(self.sku_list, checked_strings, 'name')

        release_date = datetime.datetime.strptime(self.release_date_ctrl.GetValue().Format("%Y-%m-%d"), "%Y-%m-%d").date() #20160907
        development_mm = self.textctrl_develop_mm.GetValue().strip()
        development_mm = '0' if cmp(development_mm, '') == 0 else development_mm
        maintenance_mm = self.textctrl_maintain_mm.GetValue().strip()
        maintenance_mm = '0' if cmp(maintenance_mm, '') == 0 else maintenance_mm
        version = self.textctrl_version.GetValue().strip()
        ww_version = self.textctrl_ww_version.GetValue().strip()
        is_sync_ww = self.checkbox_is_sync_ww.IsChecked()
        ww_release_date = None
        if is_sync_ww:
            ww_release_date = datetime.datetime.strptime(self.ww_release_date_ctrl.GetValue().Format("%Y-%m-%d"), "%Y-%m-%d").date() #20160907

        comment = self.textctrl_comment.GetValue().strip()

        development_mm_by_sku = float(development_mm) / checked_strings_count;
        maintenance_mm_by_sku = float(maintenance_mm) / checked_strings_count;

        save_status = True
        for sku in selected_skus:
            selected_product = Product.getOne((Product.project == selected_project.id) & (Product.sku == sku.id))
            #add_record(self, date, product, version, ww_version, development_mm, maintenance_mm, is_sync_ww, comment):

            msg = Action().RecordMgr.add_record(release_date, selected_product.id,
                                                  version, ww_version, ww_release_date,
                                                  development_mm_by_sku, maintenance_mm_by_sku,
                                                  is_sync_ww, comment)
            if msg:
                pass
            else:
                save_status = False
                self.showMessageBox(msg.message)
                break

        if save_status:
            self.EndModal(wx.ID_OK)

class RecordMgrFrame(MDIChildFrameBase.MDIChildFrameBase):
    menu_title_in_menubar = "&Record"

    def __init__(self, *args, **kwargs):
        MDIChildFrameBase.MDIChildFrameBase.__init__(self, *args, **kwargs)
        self.InitMenu()

        self.panel = wx.Panel(self)
        self.ListCtrl_RecordList = wx.ListCtrl(
            self.panel,
            - 1,
            style=wx.LC_REPORT)

        for col, text in enumerate([u'序号', u'id', u'Date', u'Product',
                                     u'Version', u'WW Version',
                                     u'开发MM', u'维护MM', u'Sync WW', u'更新时间', u'备注']):
            self.ListCtrl_RecordList.InsertColumn(col, text)

        wx.EVT_LIST_ITEM_RIGHT_CLICK(
            self.ListCtrl_RecordList,
            - 1,
            self.OnRecordListRightClick)

        self.InitData()

        self.sizer_left = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_left.Add(self.ListCtrl_RecordList, 1, wx.EXPAND | wx.ALL)
        self.panel.SetSizer(self.sizer_left)
        self.sizer_left.Fit(self)

    def InitData(self):
        self.record_list = Record.select().where(Record.deleted == False)
        self.ListCtrl_RecordList.DeleteAllItems()
        for idx, item in enumerate(self.record_list):
            index = self.ListCtrl_RecordList.InsertStringItem(sys.maxint, str(idx + 1))
            self.ListCtrl_RecordList.SetStringItem(index, 1, str(item.id))
            self.ListCtrl_RecordList.SetStringItem(index, 2, str(item.date))
            self.ListCtrl_RecordList.SetStringItem(index, 3, item.product.project.name + ' ' + item.product.sku.name)
            self.ListCtrl_RecordList.SetStringItem(index, 4, str(item.version))
            self.ListCtrl_RecordList.SetStringItem(index, 5, str(item.ww_version))
            self.ListCtrl_RecordList.SetStringItem(index, 6, str(item.development_mm))
            self.ListCtrl_RecordList.SetStringItem(index, 7, str(item.maintenance_mm))
            self.ListCtrl_RecordList.SetStringItem(index, 8, str(item.is_sync_ww))
            self.ListCtrl_RecordList.SetStringItem(index, 9, str(item.update_time))
            self.ListCtrl_RecordList.SetStringItem(index, 10, item.comment if item.comment is not None else u"")
        self.ListCtrl_RecordList.SetColumnWidth(0, 45)
        self.ListCtrl_RecordList.SetColumnWidth(1, 65)
        self.ListCtrl_RecordList.SetColumnWidth(2, 75)
        self.ListCtrl_RecordList.SetColumnWidth(3, 110)
        self.ListCtrl_RecordList.SetColumnWidth(4, 65)
        self.ListCtrl_RecordList.SetColumnWidth(5, 65)
        self.ListCtrl_RecordList.SetColumnWidth(6, 65)
        self.ListCtrl_RecordList.SetColumnWidth(10, 110)

    def InitMenu(self):
        self.menuBar_menubar_menu_items = [
            {'id': ControlID.MENUBAR_MENU_ITEM_RECORD_ADD, 'title': u'Add', 'separator': False, 'IsShown': lambda : True},
            {'id': ControlID.MENUBAR_MENU_ITEM_RECORD_REFRESH, 'title': u'Refresh', 'separator': False, 'IsShown': lambda : True,
                'hasSub': False,
                'sub' : [{'id': ControlID.MENUBAR_MENU_ITEM_CATEGORY_ADD, 'title': u"导出为CHM(UTF-8)"}]},
            ]
        self.menu = self.BuildMenuItems(self.menuBar_menubar_menu_items, self.OnMenubarMenu_Select)

    def OnMenubarMenu_Select(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.MENUBAR_MENU_ITEM_RECORD_ADD:
            dlg = AddProductDialog()
            if wx.ID_OK == dlg.ShowModal():
                self.InitData()
            dlg.Destroy()
        elif id == ControlID.MENUBAR_MENU_ITEM_RECORD_REFRESH:
            self.InitData()

    def OnRecordListRightClick(self, event):
        self.selected_row_index = event.GetText()

        self.sku_menu_itemms = [
            {'id': ControlID.SKU_LIST_MENU_VIEW, 'title': u"查看"},
            {'id': ControlID.SKU_LIST_MENU_DELETE, 'title': u"删除"}
            ]

        menu = self.BuildMenuItems(self.sku_menu_itemms, self.OnMenuSelect_SkuList)
        self.PopupMenu(menu, event.GetPoint())
        menu.Destroy()

    def OnMenuSelect_SkuList(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.SKU_LIST_MENU_DELETE:
            self.selected_row_index = int(self.selected_row_index) - 1
            msg = Action().RecordMgr.del_record(self.record_list[self.selected_row_index].id)
            if msg:
                self.InitData()
            else:
                self.showMessageBox(msg.message)

    def OnActive(self):
        #print '%s has been actived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos == -1:
            parent_menubar.Insert(1, self.menu, self.menu_title_in_menubar)

    def OnDeactive(self):
        #print '%s has been deactived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos != -1:
            parent_menubar.Remove(pos)

